//app.js
var formatRequest = require('/utils/requestModule.js')
App({
  onLaunch: function () {
    // wx.clearStorage()
    console.log(wx.getStorageSync('authorization'))
    let _self = this
    //登录
    wx.login({
      success: (res) => {
        if (res.code) {
          //发起网络请求
          _self.globalData.code = res.code
          _self.globalData.codeTime = new Date()
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      fail: function () {
        console.log('登录失败！')
      }
    })
    
  },
  getSystemConfig () {
    this.requestModule('/app/getConfig', {}, this.getConfigCallback, () => { }, 'GET')
  },
  getConfigCallback (res) {
    this.globalData.systemConfig = res.data
  },
  encodeUserinfo(encryptedData, iv, callback = () => {}) {
    // 解析获取用户数据
    if (this.globalData.code && encryptedData && iv) {
      let nowTime = new Date()
      // 如果code没有过期
      if (this.globalData.codeTime + 5 * 60 * 1000 < nowTime) {
        wx.login({
          success: (res) => {
            if (res.code) {
              //发起网络请求
              _self.globalData.code = res.code
              _self.globalData.codeTime = new Date()
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          },
          fail: function () {
            console.log('登录失败！')
          }
        })
      }
      // 获取用户openId
      // 将openId, 登录授权码， 授权码过期时间写入缓存
      wx.request({
        url: this.globalData.baseUrl + '/app/login',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        data: { encryptedData: encryptedData, iv: iv, code: this.globalData.code },
        method: 'POST',
        success: result => {
          let res = result.data
          if (res.code === 200 && res.data && res.data.status == 1) {
            let userInfo = JSON.parse(res.data.userInfo)
            this.setAppStorage(userInfo.openId, res.data.authorization)
            callback(result)
          }
        },
        fail: res => {
          console.log('login failed')
        }
      })
    }
    else {
      wx.showModal({
        title: '提示',
        content: '登录失败,尝试重新启动',
        success: () => {
          wx.reLaunch({
            url: '/pages/home/home',
          })
        }
      })
    }
  },
  setAppStorage (openId, authorization) {
    //设置app需要用到的缓存数据
      this.globalData.openId = openId
      this.globalData.authorization = authorization
      var expiredTime = +new Date() + 1 * 4 * 60 * 60 * 1000 // 四小时之后过期
      this.globalData.expiredTime = expiredTime
      try {
        wx.setStorageSync('openId', openId)
        wx.setStorageSync('authorization', authorization)
        wx.setStorageSync('EXPIREDTIME', expiredTime)
      } catch (e) {
        console.log('set openID storage failed')
      }
  },
  requestModule (url = '', params = {}, scall = (res) => { }, fcall = (res) => { }, method = 'POST') {
    let authorization = wx.getStorageSync('authorization')
    let expiredtime = wx.getStorageSync('EXPIREDTIME')
    let openid = wx.getStorageSync('openId')
    var nowtime = +new Date()
    if (authorization && expiredtime && nowtime - expiredtime < 0) {
      // 用户登录凭证未过期
      formatRequest.quest(authorization, url, params, scall, fcall, method)
    }
    else {
      // 用户登录凭证已经过期
      try {
        wx.removeStorageSync('authorization')
        wx.removeStorageSync('EXPIREDTIME')
        // 重新调用获取登录凭证的接口
        wx.request({
          url: this.globalData.baseUrl + '/app/authCode',
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          data: { openid: openid },
          method: 'POST',
          success: result => {
            let newauth = result.data.msg
            if (newauth) {
              this.setAppStorage(openid, newauth)
              // 正式发送请求
              formatRequest.quest(newauth, url, params, scall, fcall, method)
            }
          },
          fail: () => {
            
          }
        })
      } catch (e) {
        // Do something when catch error
      }
    }
  },
  onShow: function () {
    let authorization = wx.getStorageSync('authorization')
    let expiredtime = wx.getStorageSync('EXPIREDTIME')
    let openid = wx.getStorageSync('openId')
    if (authorization && expiredtime && openid) {
      this.getSystemConfig()
    }
  },
  formDirectUrl(directUrl = '', params = {}) {
    // 将上一页添加到队列中去
    let page = getCurrentPages()
    let formurl = '/' + page[page.length - 1].route
    this.globalData.historyUrlList.push(encodeURIComponent(formurl))
    this.globalData.currentURLkey = this.globalData.currentURLkey + 1
    this.directUrl(directUrl, params)
  },
  directUrl(directUrl = '', params = {}) {
    let searchParams = ''
    let conjuction = ''
    let count = 1
    if (params instanceof Object) {
      for (let key in params) {
        conjuction = count === 1 ? '?' : '&'
        searchParams = conjuction + key + '=' + params[key]
        count += 1
      }
    }
    wx.redirectTo({
      url: directUrl + searchParams
    })
  },
  navBack() {
    let url = this.globalData.historyUrlList[this.globalData.currentURLkey]
    this.globalData.historyUrlList.splice(this.globalData.currentURLkey, 1)
    this.globalData.currentURLkey = this.globalData.currentURLkey - 1
    wx.redirectTo({
      url: decodeURIComponent(url),
    })
  },
  removeQAListStorage () {
    wx.removeStorageSync('QAlist')
    wx.removeStorageSync('QAlistNum')
    wx.removeStorageSync('QAunitId')
  },
  globalData: {
    historyUrlList: [],
    currentURLkey: -1,
    baseUrl: 'https://www.hardslove.com',
    code: '',
    openId: '',
    authorization: '',
    systemConfig: {}, // 设置的系统变量 
    expiredTime: new Date(), // 登录凭证是否过期的凭证,
    isFinishedcourse: 0 //是否学习完了当前计划， 0表示未学完， 1表示i学完了
  }
})